package es.ceura.wilder.resources;

import es.ceura.wilder.configuration.Config;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Jorge Madrid
 */
public class ResourceGetter {

    private Config config;
    private final String homePath;
    private final String index;
    private final boolean canListDirs;
    private final String DIR_REGEX = "(/[^/ ]+)+/?";
    private Pattern p;
    private Matcher m;

    public ResourceGetter() {
        config = Config.INSTANCE;
        homePath = config.getConfigVar(Config.HOME);
        index = config.getConfigVar(Config.INDEX);
        canListDirs = "true".equals(config.getConfigVar(Config.LIST_DIRS));
    }

    public HTTPResource getResource(String path) throws FileNotFoundException, //TO DO REMOVE DUPLIATE CODE
            IOException, DeniedAccesException, InvalidResourceRequestException {
        HTTPResource resource;
        if ("/".equals(path)) {
            String mimeType = path.substring(path.lastIndexOf('.') + 1);
            resource = new HTTPResource(readBytesFromResource(homePath + path + index), mimeType);
            return resource;
        }
        p = Pattern.compile(DIR_REGEX);
        m = p.matcher(path);
        if (m.matches()) {
            File file = new File(homePath + path);
            if (file.isDirectory() && !canListDirs) {
                File indexFile = new File(homePath + path + index);
                if (indexFile.exists()) {
                    resource = new HTTPResource(readBytesFromResource(homePath + path + index), "");
                    return resource;
                } else {
                    throw new DeniedAccesException("Error al intentar cojer el recurso: " + path);
                }
            }
            String mimeType = path.substring(path.lastIndexOf('.') + 1);
            resource = new HTTPResource(readBytesFromResource(homePath + path), mimeType);
            return resource;
        } else {
            throw new InvalidResourceRequestException("Error al intentar cojer el recurso: " + path);
        }
    }

    private byte[] readBytesFromResource(String completePath)
            throws FileNotFoundException, IOException {
        ByteBuffer byteArray;
        byte[] buffer = new byte[Integer.parseInt(config.getConfigVar(Config.BUFFER_SIZE))];

        File resource = new File(completePath);
        try (FileInputStream inputStream = new FileInputStream(resource);
                BufferedInputStream bufferedInput = new BufferedInputStream(inputStream)) {

            byteArray = ByteBuffer.allocate(bufferedInput.available());
            int read;
            while ((read = bufferedInput.read(buffer)) != -1) {
                byteArray = byteArray.put(buffer, 0, read);
            }
            return byteArray.array();
        }
    }
}
